<template>
    <div class="mapContainer">
        <div id="tmap"></div>
       
        <div class="addressContent">
             <div style="margin-top:20px;">
                <span id="txt"></span>
                <span>当前中心点</span>
                <span id="position"></span>
            </div>
            <div class="listContent" v-for="(item,index) in addressList" :key="item.id"  @click="getCenterAnimation(item,index,$event)">
                 <div class="listItem">
                    <div class="leftContent">
                        <div class="title">{{ item.title }}</div>
                        <div class="titleTips">{{ item.address }}</div>
                    </div>
                    <div class="rightContent">
                        <!-- <span v-if="clickIndex==index">选中</span> -->
                        <van-icon v-if="clickIndex==index" name="success" color="#18AE66" />
                    </div>
                </div>
            </div>
           
        </div>
        <div class="btns">
            <van-button type="primary" @click="cancel">取消</van-button>
            <van-button type="info" @click="submit">确定</van-button>
        </div>

        <div class="centerDom"></div>
        <div class="refreshDom" @click="refreshClick">刷新</div>
        
        
    </div>
</template>
<script>
// 1. 导入axios
import axios from 'axios'
import logo from '@/assets/logo.png'
export default {
    data(){
        return{
            logo:logo,
            useravator:'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerDefault.png',
            avator:'',
            clickFlag:false, //判断是否是点击列表的flag
            location:{
                tlDeviceId:'',
                longitude:'', //经度
                latitude:'', //纬度
                address:''
            },
            locationObj:{
                tlDeviceId:'',
                longitude:'', //经度
                latitude:'', //纬度
                address:''
            },
            addressList:[],//地址信息列表
            map:{},
            clickIndex:0,
            timer:'',
            orignalLocation:{
                longitude:'', //经度
                latitude:'', //纬度
            }
        }
    },
    beforeRouteEnter (to, from, next) {
        console.log('About--beforeRouteEnter',to,from)
        next();
    },
    created(){

    },
     mounted(){
        this.avator=require('../assets/logo.png')
         this.getLocation();
         if(this.timer) clearInterval(this.timer)
        this.timer=setInterval(()=>{
            this.getLocation();
        },5000)
        setTimeout(()=>{
            this.initMap()
        },2000)
        
        
        
    },
    methods:{
        initMap(){
            let script=document.createElement('script');
            script.type='text/javascript'
            script.src=window.location.origin+'/TMap.js'
            script.onload=()=>{
                this.map=new window.TMap.Map(document.getElementById('tmap'),{
                    zoom:17.2,
                    pitch:0,
                    rotation:0,
                    draggable:true,
                    viewMode:'2D',
                    showControl:false,
                    mapZoomType:window.TMap.constants.MAP_ZOOM_TYPE_CENTER,
                    offset:{x:0,y:10}
                })
                console.log(this.map)
                 
                // 去除logo及水印
                var a = document.querySelector('canvas+div:last-child')
                a.style.display = 'none'
                
                if(this.location.latitude && this.location.longitude){
                    console.log('eeeee')
                    const center=new window.TMap.LatLng(this.location.latitude,this.location.longitude); //39.984120,116.307484
                    this.map.setCenter(center)
                    let mapCenter=this.map.getCenter(); //获取地图中心点
                    console.log('纬度'+mapCenter.getLat().toFixed(6),'经度'+mapCenter.getLng().toFixed(6))

                    //创建并初始化MultiMarker
                    let marker = new window.TMap.MultiMarker({
                        map: this.map,
                        styles: {
                            // 点标记样式//创建一个styleId为"myStyle"的样式（styles的子属性名即为styleId）
                            default: new window.TMap.MarkerStyle({
                                width: 20, // 样式宽
                                height: 20, // 样式高
                                anchor: { x: 10, y: 30 }, // 描点位置
                                src:this.useravator
                            }),
                        },
                        geometries: [
                            // 点标记数据数组
                            {
                                // 标记位置(纬度，经度，高度)
                                position: center,
                                id: 'default',
                            },
                        ],
                    });

                    //页面初始化时开始获取中心点地址
                    this.getDataList();
                    this.timer=setTimeout(()=>{
                        this.getCenterAnimation(this.addressList[0],0); //初始化选中状态并获取选中的坐标，进行组件传值
                    },1000)

                    let that=this;
                    //监听地图开始平移
                    this.map.on("panstart", function () {
                        txt.innerHTML = "地图开始平移"
                    })
                    //监听地图平移
                    this.map.on("pan",function(){
                        txt.innerHTML = "地图正在平移";
                        position.innerHTML = that.map.getCenter().toString();//获取地图中心点
                        console.log(that.map.getCenter().toString())
                    })
                    //监听地图平移结束
                    this.map.on("panend",function(){
                        txt.innerHTML = "地图结束平移";
                        console.log('纬度'+that.map.getCenter().getLat(),'经度'+that.map.getCenter().getLng())

                        // //创建并初始化MultiMarker
                        // marker.setGeometries([]); //清空点标记
                        // marker.add([
                        //     {
                        //         id: "1",   //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
                        //         styleId: 'myStyle',  //指定样式id
                        //         position: new TMap.LatLng(that.map.getCenter().getLat(),that.map.getCenter().getLng()),  //点标记坐标位置
                        //         properties: {//自定义属性
                        //             title: "marker3"
                        //         }
                        //     }
                        // ])

                        //获取坐标信息
                        if(!that.clickFlag){ //点击的是地图，且发生平移才可查数据
                            // that.clickIndex=-1;
                            that.getDataList();
                        }
                       
                    })
                    this.map.on('click',function(data){
                        console.log('点击的是地图',data)
                        that.clickFlag=false;
                        that.map.easeTo({
                            center:new window.TMap.LatLng(data.latLng.lat,data.latLng.lng)
                        },{
                            duration:500
                        })
                        that.clickIndex=0;
                    })
                    //监听地图的拖拽事件
                    this.map.on('drag',function(data){
                        console.log('鼠拖拽起的是地图',data)
                        that.clickFlag=false; //点击的不是列表，故为true;
                    })
                }
            }
            document.body.appendChild(script)
        },
        getDataList(){
             //平移结束获取周边位置坐标
            let params={
                key:'JUZBZ-LJH63-YHI3F-YKZRQ-KBJS3-SLBXB',
                location:this.map.getCenter().getLat()+','+this.map.getCenter().getLng(), //纬度，经度
                get_poi:'1', //是否返回周边地点列表
                // poi_options:{
                    radius:2000,
                    address_format:'short',
                    policy:4,
                // },
                output:'jsonp',
                // callback:'myCallback'
            }
            console.log('tttt')
            this.jsonp('https://apis.map.qq.com/ws/geocoder/v1',params).then((res)=>{
                console.log(res)
                console.log(res.result.pois)
                this.addressList=res.result.pois;
                this.clickIndex=0; //默认选择第一个
            })
        },
        //根据坐标，点标记自动变化，出现过渡动画
        getCenterAnimation(item,index,e){
            console.log(item,index,e)
            this.clickFlag=true;
            this.clickIndex=index;
            this.map.easeTo({
                center:new window.TMap.LatLng(item.location.lat,item.location.lng)
            },{
                duration:500
            })
            console.log('选中第一个',item.location)
            this.locationObj.latitude=item.location.lat;
            this.locationObj.longitude=item.location.lng;
            this.locationObj.address=item.address;
            console.log(this.locationObj)
        },
        //定位刷新
        refreshClick(){
            this.getCenterAnimation(this.orignalLocation,0);
            this.clickFlag=false;//移动的是地图
            this.getDataList();
        },
        getLocation(){
            // setTimeout(()=>{
                this.location={
                    latitude:'39.984120',
                    longitude:'116.307484',
                    address:'北四环西路66号',
                    tlDeviceId:'',
                }
                //存储最初的坐标
                this.orignalLocation={
                    location:{
                        lat:'39.984120',
                        lng:'116.307484',
                        address:'北四环西路66号',
                    }
                }
            // },2000)
            console.log('rrrrrr')
           
        },
        cancel(){
            console.log('取消')
        },
        submit(){
            console.log('提交',this.addressList[this.clickIndex],this.addressList[this.clickIndex].location)
            this.$dialog.alert({
                title:'温馨提示',
                message:'是否确认地点',
                showCancelButton:true
            }).then(()=>{
                console.log('确认提交了')
            }).catch(()=>{
                console.log('取消了')
            })
        },
        jsonp(url, data) {
            return new Promise((resolve, reject) => {
                let params = ''
                for (var k in data) {
                params += `&${k}=${data[k]}`
                }
                url = `${url}?${params.slice(1)}`

                let callbackName = `jsonp_${Date.now()}`
                window[callbackName] = (data) => {
                    resolve(data)
                    delete window[callbackName]
                    script.parentNode.removeChild(script)
                }

                let script = document.createElement('script')
                script.src = `${url}&callback=${callbackName}`
                document.body.appendChild(script)
            })
        },
    }
}
</script>
<style lang="less" scoped>
.mapContainer{
    width:100%;
    height:100vh;
    position:relative;
}
#tmap{
    width:100%;
    height:330px;
}
.addressContent{
    width:100%;
    height:calc(100vh - 330px);
    overflow: auto;
    position:absolute;
    top:320px;
    background:#fff;
    border-top-right-radius: 16px;
    border-top-left-radius: 16px;
}
.listContent{
    padding:10px 24px;
    border-bottom:1px solid #ddd;
    .listItem{
        // height:100px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .leftContent{
            width:300px;
            .title{
                margin-bottom:5px;
                font-weight: 500;
                text-align: left;
            }
            .titleTips{
                font-size:14px;
                color:#ddd;
                text-align: left;
            }
        }
        .rightContent{
            width:80px;
        }
    }
}
.btns{
    position:absolute;
    width:80%;
    top:40px;
    right:10%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    z-index:2000;
}
.centerDom{
    width:20px;
    height:20px;
    border-radius: 50%;
    background:#999;
    border:2px solid #fff;
    position:absolute;
    top:160px;
    right:calc((100% - 20px) / 2);
    box-shadow: 0px 0px 16px 8px rgba(0,101,72,0.02)
}
.refreshDom{
    width:30px;
    height:30px;
    border-radius:8px;
    background-color:#ddd;
    position:absolute;
    top:250px;
    left:20px;
    font-size:10px;
    color:#333;
    line-height:30px;
    text-align: center;
}
</style>